﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AkazoNobel.Scheduler.Core;
using AkazoNobel.Scheduler.StoreMasterData.Common;
using AkazoNobel.Scheduler.StoreMasterData.DataAccess;
using AkazoNobel.Scheduler.StoreMasterData.DataAccess.Model;
using AkazoNobel.Scheduler.StoreMasterData.DataAccess.Service;
using AkazoNobel.Ultimus.Extension;
using Dapper;
using Quartz;
using Ultimus.WFServer;

namespace AkazoNobel.Scheduler.StoreMasterData.Tasks
{
    public class TodoRemindc : BaseTask
    {
        public override void ExecuteTask(IJobExecutionContext context)
        {
            LogDebug(DateTime.Now.ToString());
            LogDebug("==== 开始发起流程 ====");

            using (var connection = SqlConnectionHelper.GetConnection(Constant.MDC_DB_NAME))
            {
                var rows = connection.Query("SELECT [email],[count] FROM [v_MdcTodoCount]").ToList();

                LogDebug(string.Format("有{0}条需要发起的流程", rows.Count));

                foreach (var row in rows)
                {
                    string email = row.email;
                    int count = row.count;

                    if (!email.Contains("@"))
                    {
                        continue;
                    }

                    var variables = new List<Variable>();
                    string applicationNo;

                    //发起流程
                    variables.Add("Recipient", email);
                    variables.Add("TodoCount", count);
                    variables.Add("Date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                    LogDebug(string.Format("Recipient:'{0}' @TodoCount:'{1}' @Date:'{2}'",
                        email.Trim(), count, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

                    TaskHelper.NewIncident("d30.intra/svc_dpcna_mdc", "Todo Remind", "Recipient的待办提醒", variables,
                        out applicationNo);
                    LogDebug("==== 流程编号" + applicationNo + " ====");

                    // 发布流程之后，线程等待1秒
                    System.Threading.Thread.Sleep(1000);
                }
            }


        }

        private void LogDebug(string content)
        {
            Console.WriteLine(content);
            Logger.Debug(content);
        }
    }
}
